// src/components/ProtectedRoute.tsx
import React, { useContext } from 'react';
import UserContext from "../context/UserContext.tsx";
import { Navigate } from "react-router-dom";

interface ProtectedRouteProps {
    children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
    const context = useContext(UserContext);

    if (!context) {
        throw new Error('UserContext must be used within UserProvider');
    }

    const { isAuthenticated, loading } = context;

    // 如果还在加载中，显示加载状态或返回 null
    if (loading) {
        return <div>Loading...</div>; // 或者返回一个加载组件
    }

    if (!isAuthenticated) {
        console.log("用户未认证 isAuthenticated", isAuthenticated);
        // 用户未认证，重定向到登录页面
        return <Navigate to="/login" />;
    }

    // 用户已认证，渲染子组件
    return <>{children}</>;
};

export default ProtectedRoute;
